# -*- coding: utf-8 -*-
'''
@author: olivia.dou
Created on: 2019/7/25 13:31
desc:
'''

import json,requests,re,logging,time
from util.crypt_util import aes_encrypt
from Crypto.Cipher import AES
from base.get_config import get_header_file,get_verify_cert,get_sync_server_time
from base.expression_evaluation import eval_from_string
import base.globalvars as glo
from proj_spec.inews.user_admin import get_user_id
from util.json_util import JsonUtil



def login(username,password):
    session = requests.Session()
    root_url = glo.get_value('url5')
    url = root_url + '/site/login'
    data = {"username": username,
            "password": password,
            "remember": 0}
    jutil = JsonUtil(get_header_file())
    header_value = jutil.get_data("header6")
    #header_str = eval_from_string(repr(header_value), return_str=True, json_str=True)
    #header = json.loads(json.dumps(eval(header_str)))
    header = eval_from_string(repr(header_value))
    r = session.post(url, data, headers=header)
    #glo.set_value("session", r.cookies.get_dict())
    r_json = r.json()
    assert r.status_code == 200, "登录失败，status code：%s"%r.status_code
    return session

def getFromToken(login=False, username="ChinaScope", delta=0):
    """

    :param login:后台接口是否需要登录,默认为False
    :param username: 用户名，用于查找uid,默认为ChinaScope
    :param delta:时间戳取距离当前时间的变化值，单位为秒,默认delta=0，时间戳为当前时间
    :return: From token
    """
    if username == "ChinaScope":
        uid = username
    else:
        uid = str(get_user_id(username))

    # 获取毫秒级时间戳
    sync_server_time=get_sync_server_time()
    if sync_server_time.lower()=='true':
        # 2019/09/26 由于前端实现修改导致调用接口不定期超时，通过接口获取服务器时间
        jutil = JsonUtil(get_header_file())
        header_value = jutil.get_data("header2")
        #verify = get_verify_str()
        #cert = get_cert()
        verify,cert = get_verify_cert()
        #res = requests.get(url = glo.get_value('url5') + "/site/get-time",headers = header_value)
        # 2020/02/04 前端改用site/time接口
        #res = requests.get(url=glo.get_value('url5') + "/site/get-time",verify=verify)
        res = requests.get(url=glo.get_value('url5') + "/site/time", verify=verify)
        if res.status_code!=200:
            assert "获取服务器时间失败"
        text = res.text
        #logging.debug(text)

        #pattern = "window.ctime=\D*(\d{13})\D*;.+"
        #inputtimestamp = int(re.match(pattern,text,re.S).group(1)) + delta * 1000
        inputtimestamp = int(text) + delta * 1000
        #logging.debug(time.localtime(inputtimestamp/1000))
    else:
        inputtimestamp = int(round(time.time() * 1000)) + delta * 1000

    if login == True:
        login = "true"
    else:
        login = "false"

    inputstr = '###{"t":%s,"u":"%s","l":%s}###' % (inputtimestamp, uid, login)
    #logging.debug(inputstr)

    # return aes_encrypt(inputstr,AES.MODE_CBC,"jSt3SttxMbBml3tc","IzMoaK3jSeBgDKQR").decode('utf-8')
    return aes_encrypt(inputstr, "jSt3SttxMbBml3tc", AES.MODE_CBC, "IzMoaK3jSeBgDKQR")